package joodle.tools;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Rectangle2D;

import joodle.domain.Point;

/**
 * <p><center>
 * <img src="http://ug.bcc.bilkent.edu.tr/~m_ozdal/Site/Reports_files/design_files/image011.jpg" />
 * </center></p>
 */
public class RotationTool extends TransformationTool {
	int degrees = 0;
	
	/**
	 * Draws an intermediate figure which consists of an arc with the rotation angle as an indicator 
	 * of RotationTool
	 * @see Tool#drawInterim(Graphics)
	 */
	@Override
	public void drawInterim(Graphics g) {
		if(transformedShape == null)
			return;
		
		super.drawInterim(g);
		Graphics2D g2 = (Graphics2D) g.create();
		g2.setColor(INTERIM_COLOR);
		
		Point c = shape.getCenter();
		Rectangle2D br = new Rectangle2D.Float(c.getX()-30, c.getY()-30, 60, 60);
		Arc2D arc = new Arc2D.Float(br, 0, degrees, Arc2D.PIE);
		g2.setStroke(INTERIM_STROKE);
		g2.draw(arc);
		g2.fill(new java.awt.geom.Ellipse2D.Float(c.getX()-2, c.getY()-2, 4, 4));
		g2.drawString(String.valueOf(degrees) + "\u00B0", c.getX(), c.getY()-2);

		g2.dispose();
	}

	/**
	 * Invoked when the mouse button has been clicked (pressed and released) on a component.
	 * @see Tool#handlePress(Point, boolean)
	 */
	@Override
	public void handlePress(Point p, boolean ctrl) {
		super.handlePress(p, ctrl);
	}

	/**
	 * Invoked when the mouse cursor has been moved onto a component. Listens the mouse movement for
	 * rotation event
	 * @see Tool#handleMove(Point, boolean, boolean)
	 */
	@Override
	public void handleMove(Point p, boolean ctrl, boolean lb) {
		if(!lb || currentPoint == null || transformedShape == null)
			return;
		float dy = p.getY() - currentPoint.getY();
		degrees = Math.round(degrees - dy) % 360;
		
		AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(dy), 
				transformedShape.getCenter().getX(), transformedShape.getCenter().getY());
		currentTransform.concatenate(at);
		transformedShape.transform(at);
			
		currentPoint = p;
	}
	
	/**
	 * Invoked when a mouse button has been released on a component.
	 * @see Tool#handleRelease(Point, boolean)
	 */
	@Override
	public void handleRelease(Point p, boolean ctrl) {
		super.handleRelease(p, ctrl);
		degrees = 0;
	}

	/**
	 * Invoked when escape key has been pressed.
	 * @see Tool#handleKeyPress(int)
	 */
	@Override
	public void handleKeyPress(int c) {
		super.handleKeyPress(c);
		if(c == KeyEvent.VK_ESCAPE)
			degrees = 0;
	}

}
